<template>
  <div class="bottomRight">
    <div class="bg-color-black">
      <div class="d-flex pt-2 pl-2">
        <i class="iconfont  icon-chuansongdai" id="cs"></i>
        <div class="d-flex">
          <span class="fs-xl text mx-2 mt-1">传送带2</span>
        </div>
      </div>
      <div class="cb">
        <div class="cb1">
          <!--  svg组件2-->
          <UpperRightCorner
              :traysData="traysData[7]"
              class="two"/>
          <div class="cb1-m">
            <ConveyerBelt
                :traysData="traysData[0]"
            />
          </div>
          <!--  svg组件1-->
          <UpperLeftCorner
              :traysData="traysData[1]"
              class="one"/>
        </div>
        <div class="cb2">
          <ConveyerBelt1
              :traysData="traysData[2]"
          />
        </div>
        <div class="cb3">
          <div>
            <!--  svg组件3-->
            <LowerLeftCorner
                :traysData="traysData[3]"
            />
          </div>
          <div class="cb3-m">
            <ConveyerBelt3
                :traysData="traysData[4]"
            />
          </div>
          <div>
            <!--  svg组件4-->
            <LowerRightCorner
                :traysData="traysData[5]"

            />
          </div>
          <div class="cb4">
            <ConveyerBelt2
                :traysData="traysData[6]"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import {defineComponent, onBeforeUnmount, ref, reactive, computed, watch} from 'vue';
import UpperRightCorner from "@/views/bottomRight2/conveyerBelt/corner/UpperRightCorner.vue";
import UpperLeftCorner from "@/views/bottomRight2/conveyerBelt/corner/UpperLeftCorner.vue";
import LowerLeftCorner from "@/views/bottomRight2/conveyerBelt/corner/LowerLeftCorner.vue";
import ConveyerBelt from "@/views/bottomRight2/conveyerBelt/ConveyerBelt.vue";
import ConveyerBelt1 from "@/views/bottomRight2/conveyerBelt/ConveyerBelt1.vue";
import ConveyerBelt2 from "@/views/bottomRight2/conveyerBelt/ConveyerBelt2.vue";
import ConveyerBelt3 from "@/views/bottomRight2/conveyerBelt/ConveyerBelt3.vue";
import LowerRightCorner from "@/views/bottomRight2/conveyerBelt/corner/LowerRightCorner.vue";

import {TrayMsg} from "@/views/bottomRight2/myDataTypes";

import {useStore} from "vuex";

interface TrayMsgItem {
  mouth: number;
  inGoods: boolean;
  errStatus: boolean;
}

export default defineComponent({
  components: {
    UpperRightCorner,
    UpperLeftCorner,
    LowerLeftCorner,
    ConveyerBelt,
    ConveyerBelt1,
    ConveyerBelt2,
    ConveyerBelt3,
    LowerRightCorner,
  },

  setup() {
    const startingTrayNumber = ref(1);

    const data = reactive<TrayMsg>({
      trayInGoods: [],
      trayErrStatus: [],
      trayMouths: Array.from({length: 432}, (_, i) => i + 1)
    })

    const mouthSegmentLengths = [99, 9, 99, 9, 99, 9, 99, 9]; // trayMouths每段的长度
    const inGoodsSegmentLengths = [99, 9, 99, 9, 99, 9, 99, 9]; // trayInGoods每段的长度
    const errStatusSegmentLengths = [99, 9, 99, 9, 99, 9, 99, 9]; // trayErrStatus每段的长度
    const startIndices = [startingTrayNumber.value - 1, 98, 107, 206, 215, 314, 323, 422]; // 每段的起始索引

    const traysData = reactive([]);
    const trayMouths = data.trayMouths;

    console.log('data.ingoods', data.trayInGoods)
    for (let i = 0; i < mouthSegmentLengths.length; i++) {
      const mouthLength = mouthSegmentLengths[i];
      const inGoodsLength = inGoodsSegmentLengths[i];
      const errStatusLength = errStatusSegmentLengths[i];
      let startIndex = startIndices[i];

      const segment = {
        // trayInGoods: data.trayInGoods.slice(startIndex, startIndex + inGoodsLength),
        // trayErrStatus: data.trayErrStatus.slice(startIndex, startIndex + errStatusLength),
        trayInGoods: Array(inGoodsLength).fill(false),
        trayErrStatus: Array(errStatusLength).fill(false),
        trayMouths: trayMouths.slice(startIndex, startIndex + mouthLength)
      };
      // console.log('sssss', segment)
      traysData.push(segment);


      if (i === mouthSegmentLengths.length - 1) {
        // 将缺失的数字添加到最后一段的末尾
        const missingNumbers = Array.from({length: startingTrayNumber.value - 1}, (_, index) => index + 1);
        // segment.trayInGoods.push(...missingNumbers.map(() => false));
        // segment.trayErrStatus.push(...missingNumbers.map(() => false));
        segment.trayMouths.push(...missingNumbers);

        // 将多出的数字依次添加到前面的数组段
        let remainingExcessNumbers = segment.trayMouths.splice(0, segment.trayMouths.length - mouthLength);
        let precedingSegmentIndex = traysData.length - 2;

        while (remainingExcessNumbers.length > 0 && precedingSegmentIndex >= 0) {
          const precedingSegment = traysData[precedingSegmentIndex];
          const numbersToAdd = remainingExcessNumbers.splice(-mouthSegmentLengths[precedingSegmentIndex]);
          // precedingSegment.trayInGoods.push(...numbersToAdd.map(() => false));
          // precedingSegment.trayErrStatus.push(...numbersToAdd.map(() => false));
          precedingSegment.trayMouths.push(...numbersToAdd);
          precedingSegmentIndex--;
        }
      }

      if (i < mouthSegmentLengths.length - 1) {
        startIndices[i + 1] = startIndex + mouthLength;
      }
    }

    // console.log(11)
    // console.log(traysData)
    // console.log(22)

    let maxMouth = 0;
    const traysCombined: TrayMsgItem[] = [];

    for (let i = 0; i < traysData.length; i++) {
      const tray = traysData[i];
      const trayMouths = tray.trayMouths;

      trayMouths.forEach((mouth, index) => {
        const inGoods = tray.trayInGoods[index];
        const errStatus = tray.trayErrStatus[index];

        const trayMsgItem: TrayMsgItem = {
          mouth: mouth,
          inGoods: inGoods,
          errStatus: errStatus,
        };

        traysCombined.push(trayMsgItem);
        maxMouth = Math.max(maxMouth, mouth);
      });

    }
    // console.log(traysCombined)


    const isTrayMovementActive = ref(true);

    //在你想要触发移动的地方，调用 moveMouths 函数
    function moveMouths(startingTrayNumber: number) {

      for (let i = 0; i < traysData.length; i++) {
        const trayMouths = traysData[i].trayMouths;
        const trayInGoods = traysData[i].trayInGoods;
        const trayErrStatus = traysData[i].trayErrStatus;

        for (let j = 0; j < trayMouths.length; j++) {
          trayMouths[j] = startingTrayNumber;

          const currentIndex = trayMouths.findIndex((mouth) => mouth === trayMouths[j]);

          const combinedItem = traysCombined.find((item) => item.mouth === trayMouths[j]);

          // console.log('是否相等',trayMouths[j],"==",combinedItem.mouth)
          if (combinedItem) {
            trayErrStatus[j] = combinedItem.errStatus;
            trayInGoods[j] = combinedItem.inGoods;
          }
          // console.log('startingTrayNumber:', startingTrayNumber); // Debugging
          // console.log('maxMouth:', maxMouth); // Debugging
          // console.log('startingTrayNumber1:', startingTrayNumber)
          startingTrayNumber++;
          if (startingTrayNumber > maxMouth) {
            // console.log('startingTrayNumber2:', startingTrayNumber)
            startingTrayNumber = 1;
            // console.log('是否执行', maxMouth)
          }
        }
      }
    }

    function startTrayMovement(startingTrayNumber: number) {
      const intervalId = setInterval(() => {
        moveMouths(startingTrayNumber);
        startingTrayNumber += 1;
        if (startingTrayNumber > maxMouth) {
          startingTrayNumber = 1;
        }
      }, 272);
      onBeforeUnmount(() => {
        clearInterval(intervalId);
      });

      // 后端更新停止时停止托盘移动
      watch(isTrayMovementActive, (newValue) => {
        if (!newValue) {
          clearInterval(intervalId);
        }
      });
    }

    // startTrayMovement(startingTrayNumber.value);

// // 模拟函数调用
//     simulateBackendUpdates(startingTrayNumber,traysCombined)

    // 模拟后端推送的消息
    // function simulateBackendUpdates(startingTrayNumber) {
    //   const previousTrayData = {}; // 保存上一次的小车状态
    //
    //   setInterval(() => {
    //     const trayData = {}; // 当前推送的小车状态
    //
    //     // 模拟生成小车的状态数据
    //     for (let i = startingTrayNumber; i <= startingTrayNumber + traysCombined.length; i++) {
    //       const trayInGoodsData = Math.random() < 0.5; // 随机生成true或false
    //       const trayErrStatusData = Math.random() < 0.2; // 随机生成true或false
    //
    //       trayData[i - startingTrayNumber] = {
    //         trayInGoodsData,
    //         trayErrStatusData
    //       };
    //     }
    //
    //     // 遍历所有小车
    //     for (let i = 0; i < traysCombined.length; i++) {
    //       //当前小车索引
    //       const trayIndex = i
    //       const currentTrayData = trayData[trayIndex];
    //       const previousTrayDataForIndex = previousTrayData[trayIndex];
    //       if (
    //           previousTrayDataForIndex &&
    //           (currentTrayData.trayInGoodsData !== previousTrayDataForIndex.trayInGoodsData ||
    //               currentTrayData.trayErrStatusData !== previousTrayDataForIndex.trayErrStatusData)
    //       ) {
    //         // 更新当前小车的值
    //         traysCombined[i].inGoods = currentTrayData.trayInGoodsData;
    //         traysCombined[i].errStatus = currentTrayData.trayErrStatusData;
    //
    //         console.log('Received update from backend: Tray', trayIndex + 1);
    //         console.log('trayInGoods:', currentTrayData.trayInGoodsData);
    //         console.log('trayErrStatus:', currentTrayData.trayErrStatusData);
    //
    //       }
    //     }
    //     // 保存当前推送的小车状态
    //     Object.assign(previousTrayData, trayData);
    //   }, 2000); // 假设每隔2秒推送一条消息
    // }

// 模拟函数调用
    function startWebSocketUpdates() {
      // 创建一个新的WebSocket连接
      var socket = new WebSocket('ws://100.100.100.200:18081/websockets/aibangplc')
      var webSocket = new WebSocket('ws://100.100.100.200:18081/plc');
      let startingTrayNumber = null;
      //建立连接后开始接收消息
      socket.onopen = function () {
        console.log('WebSocket connection opened');
        isTrayMovementActive.value = true;
      };

      webSocket.onmessage = function (event) {
        // 假设后端发送的是JSON数据
        const data = JSON.parse(event.data);
        console.log('111111', data)
        if (startingTrayNumber === null) {
          // Set the startingTrayNumber if it is not yet initialized
          startingTrayNumber = data;
          startTrayMovement(startingTrayNumber);
        }
      }

      let trayStatus = {
        trayInGoods: [],
        trayErrStatus: [],
        trayMouths: []
      };

      //处理接收到的消息
      socket.onmessage = function (event) {
        // 假设后端发送的是JSON数据
        const data2 = JSON.parse(event.data);
        console.log(data2)

        // Update the trayStatus with the received data
        if (data2.trayMsg.trayInGoods !== undefined) {
          trayStatus.trayInGoods = data2.trayMsg.trayInGoods;
        }
        if (data2.trayMsg.trayErrStatus !== undefined) {
          trayStatus.trayErrStatus = data2.trayMsg.trayErrStatus;
        }
        if (data2.trayMsg.trayMouths !== undefined) {
          trayStatus.trayMouths = data2.trayMsg.trayMouths;
        }
        // 使用接收到的数据更新前端的状态
        for (let i = 0; i < traysCombined.length; i++) {
          const trayIndex = i;

          // 如果接收到的数据和当前状态不同，更新状态
          if (
              traysCombined[i].inGoods !== trayStatus.trayInGoods[i] ||
              traysCombined[i].errStatus !== trayStatus.trayErrStatus[i]
          ) {
            traysCombined[i].inGoods = trayStatus.trayInGoods[i];
            traysCombined[i].errStatus = trayStatus.trayErrStatus[i];

            // console.log('Received update from backend: Tray', trayIndex + 1);
            // console.log('trayInGoods:', trayStatus.trayInGoods[i]);
            // console.log('trayErrStatus:', trayStatus.trayErrStatus[i]);
          }
        }
      };
      //处理连接关闭
      socket.onclose = function () {
        console.log('WebSocket connection closed');
      };

      webSocket.onclose = function () {
        console.log('WebSocket connection closed');
        isTrayMovementActive.value = false
      }
      // 处理错误
      socket.onerror = function (error) {
        console.error('WebSocket error:', error);
      };

      // 组件卸载时，关闭WebSocket连接
      onBeforeUnmount(() => {
        socket.close();
        webSocket.close();
      });
    }

    startWebSocketUpdates();
    return {traysData};
  },
});
</script>

<style lang="scss" class scoped>
$box-height: 780px;
$box-width: 100%;


.bottomRight {
  padding: 14px 16px;
  height: $box-height;
  width: $box-width;
  border-radius: 5px;

  .bg-color-black {
    height: $box-height - 30px;
    border-radius: 10px;

  }

  .text {
    color: #c3cbde;

  }

  .chart-box {
    margin-top: 16px;
    width: 170px;
    height: 170px;

    .active-ring-name {
      padding-top: 10px;
    }
  }

  .cb {
    height: $box-height - 70px;

    .one {
      transform: translate(-1011px, 60px) rotate(180deg);
    }

    .cb1 {
      display: flex;

      .cb1-m {
        transform: rotate(180deg) translate(-274px, 110px);
      }
    }

    .cb2 {
      height: 193px;
      width: 130px;
      display: flex;
      justify-content: space-between;
      overflow-x: hidden;
      overflow-y: scroll;
      background-color: #0f1325;
      margin-top: 40px;
    }

    .cb2::-webkit-scrollbar {
      display: none;
    }
  }

  .cb:deep(.item2) {
  }

  .cb3 {
    display: flex;

    .cb3-m {
      width: 1027px;
    }
  }

  .cb4 {
    height: 193px;
    transform: translate(150.5px, -191px) rotate(180deg);
    overflow-x: hidden;
    overflow-y: scroll;
  }

  .cb4::-webkit-scrollbar {
    display: none;
  }
}
</style>
